package com.example.mysimpleexample.fragment;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatButton;
import androidx.fragment.app.Fragment;

import com.example.mysimpleexample.R;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.base.XPageFragment;

import org.jetbrains.annotations.NotNull;

import java.util.List;

import butterknife.BindView;

@Page(name = "检测支付宝和微信是否安装")
public class PaypalAndWeCharFragment extends XPageFragment {
    @BindView(R.id.button1)
    AppCompatButton button1;
    @BindView(R.id.button2)
    Button button2;
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_paypal_wechat;
    }

    @Override
    protected void initViews() {

    }

    @Override
    protected void initListeners() {
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Uri uri = Uri.parse("alipays://platformapi/startApp");
                Intent intent = new Intent(Intent.ACTION_VIEW,uri);
                ComponentName componentName = intent.resolveActivity(getContext().getPackageManager());
                if (componentName != null) {
                    Toast.makeText(getActivity(), "恭喜你，安装了支付宝", Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(getActivity(), "未安装支付宝", Toast.LENGTH_SHORT).show();
                }
            }
        });

        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isInstalled = isWeiXinInstalled(getContext());
                if (isInstalled) {
                    Toast.makeText(getActivity(), "恭喜你，安装了微信", Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(getActivity(), "未安装微信", Toast.LENGTH_SHORT).show();
                }
            }
        });


    }
    private boolean isWeiXinInstalled(Context context){
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        if (packageInfos != null) {
            for (PackageInfo packageInfo : packageInfos) {
                String packageName = packageInfo.packageName;
                Log.e("packageName",packageName);
                if (packageName.equals("com.tencent.mm")) {
                    return true;
                }
            }
        }
        return false;
    }

}
